//
//  VHLSQLiteTool.swift
//  VideoEditor_Swift
//
//  Created by Vincent on 2020/5/25.
//  Copyright © 2020 Darnel Studio. All rights reserved.
//

import UIKit

public class VHLSQLiteTool: NSObject {
    #if DEBUG
    static var isDEBUG: Bool = true
    #else
    static var isDEBUG: Bool = false
    #endif
    
    // 日期格式化对象（避免重复创建）
    static var dateFormatter: DateFormatter = {
        let df = DateFormatter()
        df.dateFormat = "yyyy-MM-dd HH:mm:ss"
        df.locale = Locale(identifier: "en_US_POSIX")
        return df
    }()
    
    /// 构建数据库地址
    public static func dbPath(with direcotryBase: FileManager.SearchPathDirectory = .documentDirectory,
                           direcotry: String, fileName: String) -> String? {
        guard let directoryPath = NSSearchPathForDirectoriesInDomains(direcotryBase, .userDomainMask, true).first else {
            return nil
        }
        let directoryPathNS = (directoryPath as NSString).appendingPathComponent(direcotry)
        checkAndCreateDirectory(directory: directoryPathNS)
        
        /// 去除空格 / 判断是否有文件后缀
        var fName = fileName.trimmingCharacters(in: .whitespacesAndNewlines).replacingOccurrences(of: " ", with: "")
                
        let subffixs = ["sqlite3", "sqlite", "db"]
        if subffixs.first(where: { fName.lowercased().hasSuffix($0)}) == nil {
            fName += ".sqlite3"
        }
        
        let filePath = (directoryPathNS as NSString).appendingPathComponent(fName)
        return filePath
    }
    
    /// 检查并创建目录
    static func checkAndCreateDirectory(directory: String) {
        var isDirecotry : ObjCBool = false
        if !FileManager.default.fileExists(atPath: directory, isDirectory:&isDirecotry) {
            try? FileManager.default.createDirectory(atPath: directory, withIntermediateDirectories: true, attributes: nil)
        }
    }
}

// MARK: - 字符串处理
extension VHLSQLiteTool {
    /// 删除空格
    static func removeBlankSpace(_ name: String) -> String {
        var databaseName = name
        
        //包含空格的情况，去掉空格
        let blankSpaceStr = " "
        if name.contains(blankSpaceStr) {
            databaseName = databaseName.replacingOccurrences(of:blankSpaceStr, with:"")
        }
        
        return databaseName
    }
    
    static func valueIsNil(_ value: Any?) -> Bool {
        // 值为空不需要处理
        guard let value = value else { return true }

        if value is NSNull { return true }
        
        if (value as AnyObject).isKind(of: NSNumber.self) && ((value as! NSNumber).intValue == 0) {
            return true
        }
        
        return false
    }
}

// MARK: - base64
extension VHLSQLiteTool {
    func base64String(with data: Data?) -> String? {
        return data?.base64EncodedString()
    }
    func dataWith(base64Stirng: String?) -> Data? {
        return Data(base64Encoded: base64Stirng ?? "")
    }
}

func VHLSQLitePrint(_ items: Any..., separator: String = " ", terminator: String = "\n") {
    if !VHLSQLiteTool.isDEBUG { return }
    
    #if DEBUG
    DPrint("VHLSQLite: \(items) \(separator) \(terminator)")
    #endif
}
